import json

from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

from .models import Student,Group,Article,After,Sun,User
from rest_framework import viewsets
from rest_framework.renderers import JSONRenderer
from .serializers import StudentSerializer,GroupSerializer,ArticleSerializer,ArticleModelSerializer,AfterSerializer,SunSerializer,UserSerializer
# Create your views here.
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from django.forms import model_to_dict #这个是转字典的，要是不导入这个的话，接口返回json的时候会报错
# 返回json格式给前端


def index(request):
    ctx = {
        "code":1,
        "msg":"ok",
        "data":{
            "users":[
                {
                    "name":"老王",
                    "age":12
                },
                {
                    "name": "老王",
                    "age": 32
                },
                {
                    "name": "老王",
                    "age": 22
                }
            ]
        }
    }
    return JsonResponse(ctx)


# 数据的增删改查全部包含在viewsets里面这个类里面了
class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer


class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


# 利用序列化生成json数据
def getJson(request):
    art = Article.objects.get(id=1)
    ser = ArticleSerializer(art)
    return JsonResponse({'data':ser.data})

# 保存
def getMayJson(request):
    json_str = request.body
    req_dict = json.loads(json_str)
    print(req_dict)
    ser = ArticleSerializer(data=req_dict)
    print(ser)
    if ser.is_valid():
        ser.save()
        return JsonResponse({"code":200,"msg":"添加成功","data":req_dict})
    else:
        return JsonResponse({"code":0,"msg":ser.errors})


def upData(request,pk):
    art = Article.objects.get(id=pk)



# Django的分页器（paginator）
def student_page(request):
    json_str = request.body
    req_dict = json.loads(json_str)
    #page = request.GET.get('page',1) # 获取第几页
    print(req_dict)
    page = req_dict['page']
    limit = req_dict['limit']
    print(page)
    print(limit)
    #limit = request.GET.get('limit',3) # 每页有多少条数据

    all_count = Student.objects.all()
    paginator = Paginator(all_count,limit)
    page_1 = paginator.get_page(page)
    data_list =[]
    for i in page_1:
        mode_to = model_to_dict(i, exclude='img')  # exclude这个是转字典的时候去掉，哪个字段，就是不给哪个字段转成字典
        data_list.append(mode_to)

    print(data_list)
    #data = {"code":0,"msg":'操作成功',"data":data_list,"count":paginator.count}
    #return HttpResponse(json.dumps(data,cls=change_type,indent=4))
    return JsonResponse({"code":0,"msg":'操作成功',"data":data_list,"count":paginator.count})


# 分页器组件 接口分页
# 第一步，我们先生成一个分页器
class SelfPaginations(PageNumberPagination):
    page_size = 2  # 代表每页两条数据
    page_query_param = 'page'  # ？page= 这个参数的page，你要是改成p，就是？p=  页码
    page_size_query_param = 'size'  # ？page= 这个参数的page，你要是改成p，就是？p=  条数
    max_page_size = 100  # 临时调整最大数量限制


class StudentView(ModelViewSet):

    queryset = Student.objects.all().order_by('id')
    serializer_class = StudentSerializer
    pagination_class = SelfPaginations


# 多条件查询
# 当查询条件为两个时 Article 标题 内容
def getData(request):
    json_str = request.body
    req_dict = json.loads(json_str)
    title = ''
    content = ''
    for key,value in req_dict.items():
        if key == 'title':
            title = value
        if key == 'content':
            content = value
    if title:
        if content:
            all_result = Article.objects.filter(title__icontains=title,content__icontains=content)
        else:
            all_result = Article.objects.filter(title__icontains=title)
    else:
        if content:
            all_result = Article.objects.filter(content__icontains=content)
        else:
            all_result = Article.objects.all()
    ser = ArticleSerializer(all_result,many=True)
    return JsonResponse({"code": 0, "msg": '操作成功',"data":ser.data})


# 字典模式
#当采用字典存储字段时，可以很高效地优化编写工作
def getDict(request):
    search_dict = {}
    json_str = request.body
    req_dict = json.loads(json_str)
    title = ''
    content = ''
    for key,value in req_dict.items():
        if key == 'title':
            title = value
        if key == 'content':
            content = value


    if title:
        search_dict['title'] = title
    if content:
        search_dict['content'] = content
    all_result = Article.objects.filter(**search_dict)
    ser = ArticleSerializer(all_result, many=True)
    return JsonResponse({"code": 0, "msg": '操作成功', "data": ser.data})


# 多条件查询 加分页
def getList(request):
    search_dict = {}
    json_str = request.body
    req_dict = json.loads(json_str)
    page = req_dict['page']
    limit = req_dict['limit']
    title = ''
    content = ''
    for key,value in req_dict.items():
        if key == 'title':
            title = value
        if key == 'content':
            content = value


    if title:
        search_dict['title'] = title
    if content:
        search_dict['content'] = content
    all_result = Article.objects.filter(**search_dict)
    paginator = Paginator(all_result,limit)
    page_1 = paginator.get_page(page)
    ser = ArticleSerializer(all_result, many=True)
    return JsonResponse({"code": 0, "msg": '操作成功', "data": ser.data,"count":paginator.count})



# ModelSerializer
class JSONResponse(HttpResponse):
    def __init__(self,data,**kwargs):
        content = JSONResponse().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse,self).__init__(content,**kwargs)


@csrf_exempt
def article_list(request):
    # http://127.0.0.1:8000/drf/artciles/  get  获取所有
    if request.method == 'GET':
        articles = Article.objects.all()
        serializer = ArticleModelSerializer(articles,many=True)
        return JsonResponse({"code": 0, "msg": '操作成功', "data": serializer.data})

    elif request.method == 'POST':
        data = JSONParser().parse(request)  # 把前端传过来的json数据转成python数据类型
        serializer = ArticleModelSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status=201)
        return JsonResponse(serializer.errors,status=400)



# 编写删除和更新
@csrf_exempt
def article_detail(request,id):
    try:
        article = Article.objects.get(pk=id)
    except Article.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET': # 获取单个信息
        serializer = ArticleModelSerializer(article)
        return JsonResponse(serializer.data)
    elif request.method == 'PUT': # 修改
        data = JSONParser().parse(request)
        serializer = ArticleModelSerializer(article,data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors,status=400)
    elif request.method == 'PATCH':
        data = JSONParser().parse(request)
        ser = ArticleModelSerializer(instance=article,data=data,partial=True)
        if ser.is_valid():
            ser.save()
            return JsonResponse(ser.data)
    elif request.method == 'DELETE':  # 删除
        article.delete()
        return JsonResponse({"code": 0, "msg": '操作成功'})


# 一对一
@csrf_exempt
def after_list(request):
    #
    if request.method == 'GET':
        after = After.objects.all()
        serializer = AfterSerializer(after,many=True)
        return JsonResponse({"code": 0, "msg": '操作成功', "data": serializer.data})

    elif request.method == 'POST':
        data = JSONParser().parse(request)  # 把前端传过来的json数据转成python数据类型
        serializer = AfterSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status=201)
        return JsonResponse(serializer.errors,status=400)


@csrf_exempt
def sun_list(request):
    #
    if request.method == 'GET':
        sun = Sun.objects.all()
        serializer = SunSerializer(sun,many=True)
        return JsonResponse({"code": 0, "msg": '操作成功', "data": serializer.data})

    elif request.method == 'POST':
        data = JSONParser().parse(request)  # 把前端传过来的json数据转成python数据类型
        serializer = SunSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status=201)
        return JsonResponse(serializer.errors,status=400)


# 验证
@csrf_exempt
def user_list(request):
    if request.method == 'GET':
        users = User.objects.all()
        serializer = UserSerializer(instance=users, many=True)
        return JsonResponse({'data':serializer.data,'status':201})
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({'data':serializer.data,'status':201})
        return JsonResponse({'data': serializer.errors, 'status': 400})


@csrf_exempt
def user_detail(request, id):
    try:
        user = User.objects.get(id=id)
    except User.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = UserSerializer(user, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({'data':serializer.data,'status':201})
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        user.delete()
        return HttpResponse(status=204)